class World {
  /**
   * @description 画布
   * @type {HTMLCanvasElement}
   */
  canvas;

  /**
   * @description 图形元素
   * @type {Group[]}
   */
  groups = [];

  /**
   * @description 构造函数
   * @param {HTMLCanvasElement} canvas
   */
  constructor(canvas) {
    this.canvas = canvas;
    this.bindEvents();
  }

  /**
   * @description 添加
   * @param {Group[]} groups
   */
  add(...groups) {
    groups.forEach((group) => {
      group.setCanvas(this.canvas);
    });
    this.groups.push(...groups);
  }

  /**
   * @description 移除
   * @param {Group[]} groups
   */
  remove(...groups) {
    this.groups = this.groups.filter((group) => !groups.includes(group));
  }

  /**
   * @description 绘制
   */
  draw() {
    this.groups.forEach((group) => {
      group.canvas && group.draw();
    });
  }

  /**
   * @description 绑定事件
   */
  bindEvents() {
    /**
     * @description 触发事件
     * @param {any} ev
     * @param {number} mouseX
     * @param {number} mouseY
     */
    const emit = (ev, mouseX, mouseY) => {
      for (let shape of this.groups
        .flatMap((group) => group.children)
        .reverse()) {
        if (shape.listen && shape.contains(mouseX, mouseY)) {
          shape.event.emit(ev.type, shape, ev);
          break;
        }
      }
    };

    this.canvas.addEventListener("click", (ev) => {
      const rect = this.canvas.getBoundingClientRect();
      const mouseX = ev.clientX - rect.left;
      const mouseY = ev.clientY - rect.top;
      emit(ev, mouseX, mouseY);
    });
  }
}
